//
//  HXSelectedViewController.m
//  KD
//
//  Created by Hubery on 16/1/25.
//  Copyright © 2016年 ifly. All rights reserved.
//

#import "HXSelectedViewController.h"
#import "HXTabBarViewController.h"
#import "HXMeViewController.h"
#import "JCHATTimeOutManager.h"

@interface HXSelectedViewController ()
@property (weak, nonatomic) IBOutlet UIButton *rememberBtn;
@property (weak, nonatomic) IBOutlet UIButton *gotoLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton *gotoRegisterBtn;
@property (weak, nonatomic) IBOutlet HXColorPlaceholderTextField *phoneTextField;
@property (weak, nonatomic) IBOutlet HXColorPlaceholderTextField *pwdTextField;
@end

@implementation HXSelectedViewController

+ (void)registerLocalNotification:(NSInteger)alertTime{

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpAllBtn];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user boolForKey:AutoLogin]) {
        self.phoneTextField.text = [user objectForKey:Account];
        self.pwdTextField.text = [user objectForKey:Pwd];
    }
    if ([[UserDefaultHandler getUserDetault:kRemember] isEqualToString:RememberPwd]){
        [self.rememberBtn setBackgroundImage:[UIImage imageNamed:@"true"] forState:UIControlStateNormal];
    }
    

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSString *str = [UserDefaultHandler getUserDetault:kUsers_CellPhoneNum];
    if (![GlobalUtil isNilValue:str]) {
        self.phoneTextField.text = str;
    }
}

-(void)setUpAllBtn
{
    self.rememberBtn.layer.masksToBounds=YES;
    self.rememberBtn.layer.borderWidth=1.0f;
    self.rememberBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    
    self.gotoLoginBtn.layer.masksToBounds=YES;
    self.gotoLoginBtn.backgroundColor = [UIColor whiteColor];
    [self.gotoLoginBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    self.gotoLoginBtn.layer.cornerRadius=9.0f;
    
    self.gotoRegisterBtn.layer.masksToBounds=YES;
    self.gotoRegisterBtn.backgroundColor = [UIColor whiteColor];
    [self.gotoRegisterBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    self.gotoRegisterBtn.layer.cornerRadius=9.0f;
}


- (IBAction)rememberBtnClick:(UIButton *)sender {
    self.rememberBtn.selected = !self.rememberBtn.selected;
    if (self.rememberBtn.selected) {
        [self.rememberBtn setBackgroundImage:[UIImage imageNamed:@"true"] forState:UIControlStateNormal];
        [UserDefaultHandler saveUserDetault:RememberPwd key:kRemember];
    }else{
        [self.rememberBtn setBackgroundImage:nil forState:UIControlStateNormal];
        [UserDefaultHandler saveUserDetault:NotRememberPwd key:kRemember];
    }
}


- (IBAction)gotoLogin:(id)sender {
    
    if ([self.phoneTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![GlobalUtil validateMobile:self.phoneTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入合法手机号"];
        return;
    }
    if ([self.pwdTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
    [self.view endEditing:YES];
    
    [SVProgressHUD showWithStatus:@"正在登录..."];
    [NetworkAPI login:self.phoneTextField.text
         withPassword:self.pwdTextField.text
//                    number:3
                   success:^(HXLoginModel *result) {
                       if ([result.code isEqualToString:@"200"]) {
                           [UserDefaultHandler saveUserDetault:result.result.Users_CellPhoneNum key:kUsers_CellPhoneNum];
                           //登录极光
                           [self loadCreateLoginSaveWithModel:result];
       
                       }else if ([result.code isEqualToString:@"400"]){
                           [SVProgressHUD showErrorWithStatus:@"手机号或者密码错误"];
                       }else{
                           [SVProgressHUD showErrorWithStatus:@"手机号或者密码错误"];
                       }
                   } failure:^(NSError *err) {
                       [SVProgressHUD showErrorWithStatus:@"网络延时,请重新登录"];
                   }];
}

/*-----登陆极光推送
-(void)loadCreateJPushWithAlias:(HXLoginModel *)result{
    [JPUSHService setTags:[[NSSet alloc] init] alias:result.result.Users_Alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        
        NSLog(@"##########---极光推送登陆--%d--#######",iResCode);
        
        if (iResCode == 0) {
            [UserDefaultHandler saveUserDetault:@"yes" key:kIResCodeIs0Jpush];
        }else{
            if (![[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
                [self loadCreateJPushWithAlias:result];
            }
        }
    }];
}

- (void)newLoginJPushWithModel:(HXLoginModel *)result{
    
    [[JCHATTimeOutManager ins] startTimerWithVC:self];
    [JMSGUser loginWithUsername:result.result.Users_Alias
                       password:result.result.Users_PassWord
              completionHandler:^(id resultObject, NSError *error) {
                 
                  if (error == nil) {
                       [[JCHATTimeOutManager ins] stopTimer];
                      [UserDefaultHandler saveUserDetault:@"no" key:kIResCodeIs0Jpush];
                      [self loadCreateJPushWithAlias:result];
                      [self loadCreateLoginSaveWithModel:result];
                      
                    }else if (error.code == 863006) {
                         [[JCHATTimeOutManager ins] stopTimer];
                        [UserDefaultHandler saveUserDetault:@"yes" key:kIResCodeIs0Jpush];
                        [self loadCreateLoginSaveWithModel:result];
                  }
                  else {
                      JCHATMAINTHREAD(^{
                          [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                      });
                      [MBProgressHUD showMessage:[JCHATStringUtils errorAlert:error] view:self.view];
                  }
              }];
}
 */

/**
 * 进行极光推送的登录
 */
-(void)loadCreateJPushWithAlias{
    
    [JPUSHService setTags:[[NSSet alloc] init] alias:[UserDefaultHandler getUserDetault:kUsers_Alias] fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        
        NSLog(@"##########---极光推送登陆--%d--#######",iResCode);
        
        if (iResCode == 0) {
            [UserDefaultHandler saveUserDetault:@"yes" key:kIResCodeIs0Jpush];
        }else{
            if (![[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
//                [HXSelectedViewController loadCreateJPushWithAlias];
            }
        }
    }];
}

-(void)loadLoginJPush:(NSTimer *)timer{
    if ([[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
        [timer invalidate];
        timer = nil;
        return;
    }
    [self loadCreateJPushWithAlias];
}

/**
 *进行极光登录
 */
-(void)loadCreateNewLoginJPush{
    
    [JMSGUser loginWithUsername:[UserDefaultHandler getUserDetault:kUsers_Alias]
                       password:[UserDefaultHandler getUserDetault:kUsers_PassWord]
              completionHandler:^(id resultObject, NSError *error) {
                  
                  if (error == nil) {
                      [UserDefaultHandler saveUserDetault:@"yes" key:kIsLoginJpush];//极光登录为yes 登录成功
                      [UserDefaultHandler saveUserDetault:@"no" key:kIResCodeIs0Jpush];
                      [self loadCreateJPushWithAlias];
                      [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(loadLoginJPush:) userInfo:nil repeats:NO];
                  }else if (error.code == 863006) {
                      [UserDefaultHandler saveUserDetault:@"yes" key:kIsLoginJpush];//极光登录为yes 登录成功
                      if (![[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
                          [self loadCreateJPushWithAlias];
                          [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(loadLoginJPush:) userInfo:nil repeats:NO];
                      }
                  }else {
                      JCHATMAINTHREAD(^{
                          [SVProgressHUD dismiss];
                      });
                      [SVProgressHUD showErrorWithStatus:[JCHATStringUtils errorAlert:error]];
                  }
              }];

}

/**存储数据*/
-(void)loadCreateLoginSaveWithModel:(HXLoginModel *)result{
    
    [UserDefaultHandler saveUserDetault:result.result.ID key:kID];
    [UserDefaultHandler saveUserDetault:@"no" key:kIsRegisterJpush];
    [UserDefaultHandler saveUserDetault:@"no" key:kIsLoginJpush];
    [UserDefaultHandler saveUserDetault:result.result.Users_Organization key:kUsers_Organization];
    [UserDefaultHandler saveUserDetault:result.result.Users_PassWord key:kUsers_PassWord];
    [UserDefaultHandler saveUserDetault:result.result.Users_CorpName key:kUsers_CorpName];
    [UserDefaultHandler saveUserDetault:result.result.Users_IDCard key:kUsers_IDCard];
    [UserDefaultHandler saveUserDetault:result.result.Users_Kind key:kUsers_Kind];
    [UserDefaultHandler saveUserDetault:result.result.Users_RegisterDate key:kUsers_RegisterDate];
    [UserDefaultHandler saveUserDetault:result.result.Users_IsDel key:kUsers_IsDel];
    [UserDefaultHandler saveUserDetault:result.result.Users_Guid key:kUsers_Guid];
    [UserDefaultHandler saveUserDetault:result.result.Users_PersonName key:kUsers_PersonName];
    [UserDefaultHandler saveUserDetault:result.result.Users_CorpKind key:kUsers_CorpKind];
    [UserDefaultHandler saveUserDetault:result.result.Users_AppID key:kUsers_AppID];
    [UserDefaultHandler saveUserDetault:result.result.Users_AreaCode key:kUsers_AreaCode];
    [UserDefaultHandler saveUserDetault:result.result.Users_TableName key:kUsers_TableName];
    [UserDefaultHandler saveUserDetault:result.result.Users_PKCode key:kUsers_PKCode];
    [UserDefaultHandler saveUserDetault:result.result.Users_Alias key:kUsers_Alias];
    [UserDefaultHandler saveUserDetault:result.result.Users_JobName key:kUsers_JobName];
    [UserDefaultHandler saveUserDetault:result.result.Users_CorpKindName key:kUsers_CorpKindName];
    [UserDefaultHandler saveUserDetault:result.result.Users_AreaName key:kUsers_AreaName];
    [UserDefaultHandler saveUserDetault:result.result.Users_IsPayVip key:Users_IsPayVip];
    [UserDefaultHandler saveUserDetault:result.result.Users_Alias key:kUsers_Alias];//极光账号
    [UserDefaultHandler saveUserDetault:result.result.Users_PassWord key:kUsers_PassWord];//极光密码  也是用户密码
    [UserDefaultHandler runSave];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kupdateUserInfo object:nil];
    
//    [HXSelectedViewController loadCreateNewLoginJPush];
    
    HXTabBarViewController * hxTabBar = [[HXTabBarViewController alloc] init];
    hxTabBar.userKind = result.result.Users_Kind;
    UIWindow *win = [[UIApplication sharedApplication].delegate window];
    win.rootViewController = hxTabBar;
    [win makeKeyAndVisible];
    [SVProgressHUD showSuccessWithStatus:@"登陆成功,请稍后..."];
}


- (IBAction)gotoRegister:(id)sender {
}


@end
